package cn.edu.njnu.opengmpback.common.utils;

import org.apache.commons.io.IOUtils;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created by HeYuanqing on 2024/01/02  10:30
 **/
public class IoUtil {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(IoUtil.class);

    /**
     * @param path 文件路径
     * @return: byte[]
     * @Description: 将文件读出装入byte数组中
     * @Author: HeYuanqing
     * @Date: 2022/11/21 20:52
     */
    public static byte[] toByteArray(String path) {
        FileInputStream is = null;
        try {
            File file = new File(path);
            if (file != null && file.exists()) {
                is = new FileInputStream(file);
                return IOUtils.toByteArray(is);
            }
            return null;
        } catch (IOException e) {
            log.error("读取" + path + "文件成byte数组失败", e);
            return null;
        } finally {
            close(is, null);
        }
    }

    /**
     * @param inputStream 输入流
     * @return: byte[]
     * @Description: 将输入流读出装入byte数组中
     * @Author: HeYuanqing
     * @Date: 2022/11/21 20:52
     */
    public static byte[] toByteArray(InputStream inputStream) {
        try {
            return IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            log.error("读取输入流成byte数组失败", e);
            return null;
        }
    }

    /**
     * @param path     本地文件路径
     * @param encoding 编码
     * @return: java.io.InputStream
     * @Description: 将本地文件读成输入流
     * @Author: HeYuanqing
     * @Date: 2022/11/21 20:57
     */
    public static InputStream toInputStream(String path, String encoding) throws IOException {

        return IOUtils.toInputStream(path, encoding);
    }

    /**
     * @param is 输入流
     * @param os 输出流
     * @return: void
     * @Description: 关闭输入流和输出流
     * @Author: HeYuanqing
     * @Date: 2022/11/21 20:53
     */
    public synchronized static void close(InputStream is, OutputStream os) {
        try {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            log.info("关闭读写流失败", e);
        }
    }

    /**
     * @param path 文件路径
     * @return: java.lang.String
     * @Description: 转为Linux系统路径
     * @Author: HeYuanqing
     * @Date: 2022/11/21 20:54
     */
    public static String convertLinuxPath(String path) {
        String osName = System.getProperty("os.name");
        if ("Linux".equals(osName)) {
            if (path.contains(":")) {
                path = path.substring(2);
            }
//            path = StringUtils.replaceAll(path, "\\", "/");
        }
        return path;
    }
}
